<template>
  <view class="container">
    <view class="viewports" v-if="fee && fee.carAssetFeeList && fee.carAssetFeeList.length">
      <ve-card
        :title="getFeeCategoryName(item)"
        type="none"
        fold="true"
        v-for="(item, index) in fee.carAssetFeeList"
        :key="item.id"
        :customContentStyle="{
          marginBottom: 0,
        }"
      >
        <template #status>
          <view class="status-4">{{ item.feeTypeName }}</view>
          <view class="status-3">{{ item.costTypeName }}</view>
        </template>
        <ve-cell-price :label="item.costType == 0 ? '应收金额' : '应付金额'" :value="item.totalAmount"></ve-cell-price>
        <ve-cell-price :label="item.costType == 0 ? '待收金额' : '待付金额'" :value="item.totalAmount"></ve-cell-price>
        <view class="line"></view>
        <ve-cell>
          <template #label>
            <!-- pages/asset/car-manager/confirm-fee -->
            <!-- 车辆购置费|| 车辆购置补充费 -->
            <text v-if="item.feeCategory == 0 || item.feeCategory == 5">车辆购置单号</text>
            <!-- 车辆借调费 -->
            <text v-else-if="item.feeCategory == 6">借调单号</text>
            <text v-else>车辆费用单号</text>
          </template>
          {{ item.businesCode || '-' }}
        </ve-cell>
        <ve-cell :label="`${item.supplierType === 1 ? '汽车销售供应商' : '借调同行'}`">{{ item.supplierName || '-' }}</ve-cell>
        <ve-cell label="车牌号">{{ item.carLicenseNo || '-' }}</ve-cell>
        <!-- 车辆借调费显示借调周期 -->
        <ve-cell label="借调周期" v-if="item.feeCategory == 6">
          <text v-if="item.startTime || item.endTime"
            >{{ item.startTime ? item.startTime : '-' }} 至 {{ item.endTime ? item.endTime : '-' }}</text
          >
          <text v-else>-</text>
        </ve-cell>
        <view class="fee-item">
          <view class="fee-table">
            <!-- 表头 -->
            <view class="tlt">
              <view class="table-item item-1">费用名称</view>
              <view class="table-item item-2">费用金额</view>
              <view class="table-item item-3">备注</view>
            </view>
            <view style="border: 2rpx solid #f7f8fa; padding-bottom: 32rpx">
              <view class="fee-other" v-if="item.feeDetailList && item.feeDetailList.length > 0 && !item.open">
                <view class="twice" v-for="(el, elindex) in item.feeDetailList" :key="elindex">
                  <view class="table-item item-1">
                    {{ getFeeName(item, el) }}
                  </view>
                  <view class="table-item item-2">{{ el.amount }}</view>
                  <view class="table-item item-3">{{ el.remark }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <ve-gap size="24"></ve-gap>
      </ve-card>
      <!-- 表单 -->
      <ve-form ref="formRef" :model="form" :rules="rules">
        <ve-card style="overflow: hidden" type="none">
          <ve-form-item :label="costName + '时间'" required prop="paymentTime">
            <ve-date-picker v-model="form.paymentTime" title="时间" :params="datetimeparams"></ve-date-picker>
          </ve-form-item>
          <ve-form-item
            :label="costName + '方式'"
            required
            prop="paymentWay"
            labelTooltipContent="收/付款方式支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <ve-picker-inline
              v-model="form.paymentWay"
              placeholder="请选择"
              :range="paywayEnum"
              unit="arrowRight"
              @change="typeChange"
            ></ve-picker-inline>
          </ve-form-item>
          <ve-form-item :label="costName + '账号'" labelTooltipContent="收/付款账号支持在系统管理菜单下的收支账号管理页面进行配置。">
            <ve-picker-inline v-model="form.account" placeholder="请选择" :range="accountList" unit="arrowRight"></ve-picker-inline>
          </ve-form-item>
          <ve-form-item :label="costName + '金额'" unit="元" required prop="actualAmount">
            <ve-input-number v-model="form.actualAmount" :min="0" :max="99999999.99" :precision="2" :disabled="true" placeholder="请输入" />
          </ve-form-item>
          <ve-form-item label="客户名称" required prop="customerName">
            <remote-select
              v-if="supplierType === '1'"
              type="customerNameSelect"
              :label="form.customerName"
              v-model="form.customerId"
              @change="customerChange"
            />
            <remote-select
              v-if="supplierType === '0'"
              type="peerAll"
              :label="form.customerName"
              v-model="form.customerId"
              @change="customerChange"
            />
          </ve-form-item>
          <ve-form-item :label="costName == '收款' ? '客户付款账号' : '客户收款账号'">
            <ve-input v-model="form.customerAccount" placeholder="请输入" />
          </ve-form-item>
          <ve-form-item label="费用备注" :borderBottom="false" labelPosition="top">
            <ve-input type="textarea" v-model="form.settlementRemark" placeholder="请输入备注" />
          </ve-form-item>
        </ve-card>
      </ve-form>
    </view>
    <view style="height: 277rpx">
      <ve-bottom-box>
        <view class="bottom-btns">
          <view class="amount">
            {{ costName }}金额：
            <text class="amount-num">{{ receiveAmount }} </text>
            <text class="amount-pic">元</text>
          </view>
          <view class="line"></view>
          <ve-button type="primary" :loading="loading" @click="formSubmit" style="width: 100%">确认</ve-button>
        </view>
      </ve-bottom-box>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { getAccountByPageData, getAccountByWayAndType } from '@/api/dict/detail'
  import { getConfirmAssetFeeDetail, confirmAssetFee } from '@/api/asset/asset-fee'
  const loading = ref(false)
  const datetimeparams = ref({
    year: true,
    month: true,
    day: true,
    hour: true,
    minute: true,
    second: true,
  })
  const costType = ref(null)
  const pagefrom = ref(null) //判断页面回退 expense详情页  mergeConfirm合并页
  const receiveAmount = ref(0)
  const receivedNotAmount = ref(0)
  const paywayEnum = ref() //收付款方式
  const accountList = ref(null) //收付款账号
  const costName = ref() //收款or付款
  const idList = ref([])
  const fee = ref<any>()
  const form = ref<any>({})
  const rules = {
    paymentTime: {
      required: true,
      message: '请选择',
    },
    paymentWay: {
      required: true,
      message: '请选择',
    },
    actualAmount: {
      required: true,
      message: '请输入',
    },
    customerName: {
      required: true,
      message: '请输入',
    },
  }

  const getDetail = async () => {
    const res: any = await getConfirmAssetFeeDetail({ idList: idList.value })
    console.log(res.result)
    receiveAmount.value = Math.abs(res.result.receiveAmount) //合计（取绝对值）
    receivedNotAmount.value = Math.abs(res.result.receivedNotAmount) //待收付款（取绝对值）

    var datafee = res.result
    fee.value = datafee
    console.log(fee, 'fee')
    // costType 和 costName 决定底部表单为收款还是付款
    costType.value = res.result.costType
    if (costType.value == 0) {
      costName.value = '收款'
    } else {
      costName.value = '付款'
    }
    // form.value.orderId = fee.value.carAssetFeeList[0].orderId
    form.value.actualAmount = Math.abs(res.result.receiveAmount)
    form.value.paymentTime = datafee.carAssetFeeList[0].createTime
    form.value.customerName = datafee.carAssetFeeList[0].supplierName
    form.value.customerId = datafee.carAssetFeeList[0].supplierId
    form.value.paymentWay = datafee.carAssetFeeList[0].payType
    form.value.customerAccount = datafee.receiveAccount
    getType()
  }

  // 费用一级名称
  const getFeeCategoryName = (fee: any) => {
    const { feeCategory, installment, feeCategoryName, feeName, feeDetailList } = fee
    // 车辆购置费-手动添加
    if (feeCategory == 5) {
      return feeName
      // 借调费
    } else if (feeCategory == 6) {
      // 批量结算，此时只显示一级名称
      if (feeDetailList.length > 1) {
        return feeCategoryName
      } else {
        // 分期显示一级+二级名称
        if (installment == 1) {
          return feeCategoryName + '-' + feeName
        } else {
          return feeName
        }
      }
    } else {
      if (feeDetailList.length > 1) {
        return feeCategoryName
      } else {
        return feeCategoryName + '-' + feeName
      }
    }
  }

  // 费用二级名称
  const getFeeName = (fee: any, feeChild: any) => {
    const { feeCategory, installment, feeCategoryName } = fee
    const feeName = feeChild.itemName
    // 车辆购置费-手动添加
    if (feeCategory == 5) {
      return feeName
      // 借调费
    } else if (feeCategory == 6) {
      // 分期显示一级+二级名称
      if (installment == 1) {
        return feeCategoryName + '-' + feeName
      } else {
        return feeName
      }
    } else {
      return feeCategoryName + '-' + feeName
    }
  }
  // 收付款类型（方式）
  const getType = () => {
    getAccountByPageData({ type: costType.value == 0 ? 0 : 1 }).then((res: any) => {
      var children = res.result
        .map((childItem: any) => {
          return {
            value: childItem.way,
            label: childItem.wayStr,
            type: childItem.type,
          }
        })
        .filter(
          (item: any) =>
            item.value !== '0' &&
            item.value !== '1' &&
            item.value !== '2' &&
            item.value !== '3' &&
            item.value !== '4' &&
            item.value !== '5' &&
            item.value !== '-1',
        )
      paywayEnum.value = children

      children.forEach((el: any) => {
        if (el.value == form.value.paymentWay) {
          getAccountByWayAndType({ way: Number(el.value), type: Number(el.type) }).then((res: any) => {
            var children = res.result.map((childItem: any) => {
              return {
                value: childItem.id,
                label: childItem.bank + ' ' + childItem.account,
              }
            })
            accountList.value = children
          })
        }
      })
    })
  }
  // 账号
  const typeChange = (value: any) => {
    console.log(value, 'typeChange')
    if (value) {
      form.value.account = ''
    }
    getType()
  }

  const customerChange = (value: any, option: any) => {
    console.log(value, option)
    form.value.customerName = option.industryName || option.supplierName
  }

  const formRef = ref()
  // 提交
  const formSubmit = () => {
    loading.value = true
    formRef.value.validate(async (valid: any, error: any) => {
      console.log(form.value, valid, error)
      if (valid) {
        const res: any = await confirmAssetFee({ ...form.value })
        if (res.code == 200) {
          uni.showToast({
            icon: 'none',
            title: res.message,
          })
          setTimeout(() => {
            if (pagefrom.value == 'expense') {
              uni.navigateBack({ delta: 1 })
              loading.value = false
            }
            if (pagefrom.value == 'mergeConfirm') {
              uni.navigateBack({ delta: 2 })
              loading.value = false
            }
          }, 500)
        } else {
          loading.value = false
          uni.showToast({
            icon: 'none',
            title: '请选择费项',
          })
          return false
        }
      } else {
        loading.value = false
      }
    })
  }

  const supplierType = ref()
  onLoad((options: any) => {
    console.log(options, 'comfirm-fee')

    if (options.idList && options.carId) {
      supplierType.value = options.supplierType
      idList.value = JSON.parse(options.idList)
      form.value.idList = idList.value
      form.value.customerType = options.supplierType
      getDetail()
    }
    if (options.pagefrom) {
      pagefrom.value = options.pagefrom
    }
  })
</script>

<style lang="less" scoped>
  .container {
    height: auto;
    min-height: 100%;
  }
  .viewports {
    display: flex;
    flex-direction: column;
    padding: 24rpx 24rpx 0;
  }
  .status-3 {
    background-color: rgba(255, 247, 232, 1);
    color: #ff7d00;
    border: 2rpx solid #ff7d00;
    border-radius: 450rpx;
    padding: 0 16rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
  .status-4 {
    background: rgba(232, 247, 255, 1);
    color: rgba(52, 145, 250, 1);
    border: 2rpx solid rgba(52, 145, 250, 1);
    border-radius: 450rpx;
    padding: 0 16rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    margin-left: 10rpx;
  }

  .fee-item {
    overflow-x: scroll;
    margin-top: 24rpx;
    .fee-table {
      width: 800rpx;
      .tlt,
      .fee-first,
      .twice {
        width: 100%;
        background: #f7f8fa;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: #8491a8;
        font-size: 24rpx;
        font-weight: 400;
      }

      .fee-first,
      .twice {
        background: #ffffff;
        color: #191c27;
        font-size: 28rpx;
      }

      .table-item {
        padding: 24rpx 24rpx;
      }
      .item-1 {
        width: 300rpx;
      }
      .item-2 {
        width: 160rpx;
      }
      .item-3 {
        width: 160rpx;
      }
      .item-4 {
        width: 230rpx;
      }
      .item-5 {
        width: 420rpx;
      }

      .twice {
        // .item-1 {
        //   width: 350rpx - 24rpx;
        // }
      }
    }
  }
  .bottom-btns {
    width: 100%;
    display: flex;
    flex-direction: column;
    .amount {
      color: #1e1e1e;
      font-size: 32rpx;
      font-weight: 400;
      display: flex;
      justify-content: flex-start;
      align-items: flex-end;
      margin: 12rpx 0 36rpx;
      .amount-num {
        color: #fe615a;
        font-size: 48rpx;
        font-weight: 600;
        line-height: 1;
      }
      .amount-pic {
        color: #fe615a;
        font-size: 24rpx;
        font-weight: 400;
        margin-left: 8rpx;
      }
    }
  }
  .line {
    width: 100%;
    background: rgba(216, 216, 216, 0.8);
    height: 1rpx;
    margin-bottom: 32rpx;
    transform: scaleY(0.5);
  }
  :deep(.ve_tooltip__popper) {
    width: 420rpx;
    line-height: 38rpx;
    white-space: normal;
  }
</style>
